var db = require('../models');
var async = require('async');

//保存房间
exports.saveRoom = function(roomName,callback){
	var newRoom = new db.Room();
	newRoom.roomName = roomName;
	newRoom.save(callback);
}
//查找所有的房间
exports.getAllRooms = function(callback){

	db.Room.find({},function(err,rooms){
		if(err){
			return callback(err);
		}else{
			var roomsData = [];
			async.each(rooms,function(room,cb){
				var roomData = room.toObject();
				db.User.find({
					_roomId:roomData._id,
					online:true,
				},function(err,users){
					if(err){
						return callback(err);
					}else{
						roomData.users = users;
						roomsData.push(roomData);
						cb();
					}
				});
			},function(err){
				callback(err,roomsData);
			});
		}
	});
}
exports.getRoomByRoomId = function(_roomId,callback){
	db.Room.findOne({
		_id:_roomId,
	},function(err,room){
		if(err){
			callback(err);
		}else{
			async.parallel({
				'users':function(cb){
					db.User.find({
						_roomId:room._id,
						online:true
					},cb);
				},
				'messages':function(cb){
					db.Message.find({
						_roomId:room._id
					}).sort({mtime:-1}).limit(20).exec(function(err,messages){
						cb(err,messages.reverse());
					});
				}
			},function(err,results){
				if(err){
					callback(err);
				}else{
					var room = {};
					room.users = results.users;
					room.messages = results.messages;
					callback(null,room);
				}
			});
		}
	})
}
